<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *      [PinTuXiu] (C)2001-2099 ONightjar.com Pintuxiu.com.
 *      This is NOT a freeware, use is subject to license terms
 */

class upgrade_db extends Model{
	
	public function dbsize() {
		$dbsize = 0;
		$rs = $this->findSql("SHOW TABLE STATUS LIKE '".$this->dbpre."%'", 'SILENT');
		foreach ($rs as $table){
			$dbsize += $table['Data_length'] + $table['Index_length'];
		}
		return $dbsize;
	}
	
	
	public function upgradeFromFile(){
		$sql = explode(";",file_get_contents(APPPATH.'modules/upgrade/upgrade.sql'));
		foreach($sql as $query){
			if(trim($query) == '') continue;
			$query = str_replace('{dbpre}', $this->dbpre, $query);
			$result = $this->runSql($query);
			if (!$result) {
				$message  = 'Invalid query: ' . $query . "\n<br />";
				$message .= 'Whole query: ' . $query;
				return array('status'=>500,'msg'=> $message );
			}
		}
		$sql = explode("**spt**",file_get_contents(APPPATH.'modules/upgrade/settings.sql'));
		foreach($sql as $query){
			if(trim($query) == '') continue;
			$query = str_replace('{dbpre}',  $this->dbpre, $query);
			$result = $this->runSql($query);
			if (!$result) {
				$message  = 'Invalid query: ' . mysql_error() . "\n<br />";
				$message .= 'Whole query: ' . $query;
				return array('status'=>500,'msg'=> $message );
			}
		}
		
		return array('status'=>200,'msg'=> 'success' );
	}
	
	public function upgradeFromVersion(){
		$version = config_item('pzrelease','version');
		$sql = explode(";",file_get_contents(APPPATH.'modules/upgrade/up'.$version.'.sql'));
		foreach($sql as $query){
			if(trim($query) == '') continue;
			$query = str_replace('{dbpre}', $this->dbpre, $query);
			$result = $this->runSql($query);
			if (!$result) {
				$message  = 'Invalid query: ' . $query . "\n<br />";
				$message .= 'Whole query: ' . $query;
				return array('status'=>500,'msg'=> $message );
			}
		}
		return array('status'=>200,'msg'=> 'success' );
	}
	
}